﻿using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
using WAU.DTOs.OrderModule;
using WAU.Library.RabbitMQ;
using WAU.Models.Framework;
using RabbitMQChannel = RabbitMQ.Client.IModel;

namespace WAU.Services.Routines
{
    /// <summary>
    /// 消息队列消费订单 Routine
    /// </summary>
    public class MQConsumeOrderExpireRoutine : IRoutine
    {
        public const string ORDER_EXPIRE_EXCHANGE_NAME = "order_expire_exchange";
        public const string ORDER_EXPIRE_QUEUE_NAME = "order_expire_queue";

        //public static readonly int[] EXPIRE_CHECK_MINUTES_ARRAY = new int[5] { 3, 5, 6, 8, 10 };
        public static readonly int[] EXPIRE_CHECK_MINUTES_ARRAY = new int[3] { 1, 2, 3 }; 

        /// <summary>
        /// Execute
        /// </summary>
        public void Execute()
        {
            Task.Run(() =>
            {
                IServiceScope serviceScope = GlobalReadOnlyVariables.ServiceProvider.CreateScope();
                RabbitMQChannel channel = serviceScope.ServiceProvider.GetRequiredService<ScopedRabbitMQModelLease>().Channel;

                // 声明延迟交换机的类型（与默认的交换机类型相同）
                Dictionary<string, object> exchangeParamsDic = new Dictionary<string, object>
                {
                    { "x-delayed-type", "direct" }
                };
                // 声明延迟交换机（如果没有则自动创建）
                channel.ExchangeDeclare(ORDER_EXPIRE_EXCHANGE_NAME, "x-delayed-message", true, false, exchangeParamsDic);
                channel.QueueDeclare(ORDER_EXPIRE_QUEUE_NAME, true, false, false);
                channel.QueueBind(ORDER_EXPIRE_QUEUE_NAME, ORDER_EXPIRE_EXCHANGE_NAME, "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (sender, args) =>
                {
                    // 读取并反序列化 MQ 消息内容
                    string originMsg = Encoding.UTF8.GetString(args.Body.ToArray());
                    Console.WriteLine($"收到了订单过期检测消息 {originMsg}，当前时间为：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    OrderExpireCheckMQDto expireCheckMQDto = JsonSerializer.Deserialize<OrderExpireCheckMQDto>(originMsg);

                    // 创建订单
                    using (IServiceScope optServiceScope = GlobalReadOnlyVariables.ServiceProvider.CreateScope())
                    {
                        OrderService orderService = optServiceScope.ServiceProvider.GetRequiredService<OrderService>();
                        ExecResult execResult = orderService.ExpireCheck(expireCheckMQDto);
                        Console.WriteLine(execResult.ErrorMsg);
                    }
                };

                channel.BasicConsume(ORDER_EXPIRE_QUEUE_NAME, true, consumer);
            });
        }
    }
}
